package com.atguigu.gulimall.product.service.impl;

import com.atguigu.gulimall.product.dao.AttrAttrgroupRelationDao;
import com.atguigu.gulimall.product.dao.AttrDao;
import com.atguigu.gulimall.product.entity.AttrAttrgroupRelationEntity;
import com.atguigu.gulimall.product.entity.AttrEntity;
import com.atguigu.gulimall.product.service.AttrService;
import com.atguigu.gulimall.product.vo.AttrGroupVo;
import com.atguigu.gulimall.product.vo.AttrVo;
import com.atguigu.gulimall.product.vo.CategoryGroupAttrRelationAttrVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.gulimall.common.utils.PageUtils;
import com.atguigu.gulimall.common.utils.Query;

import com.atguigu.gulimall.product.dao.AttrGroupDao;
import com.atguigu.gulimall.product.entity.AttrGroupEntity;
import com.atguigu.gulimall.product.service.AttrGroupService;
import org.springframework.transaction.annotation.Transactional;

@Slf4j
@Service("attrGroupService")
public class AttrGroupServiceImpl extends ServiceImpl<AttrGroupDao, AttrGroupEntity> implements AttrGroupService {

    @Autowired
    private AttrAttrgroupRelationDao attrAttrgroupRelationDao;

    @Autowired
    private AttrDao attrDao;

    @Autowired
    private AttrService attrService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrGroupEntity> page = this.page(
                new Query<AttrGroupEntity>().getPage(params),
                new QueryWrapper<AttrGroupEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPage(Map<String, Object> params, Long catelogId) {
        String key = (String) params.get("key");
        QueryWrapper<AttrGroupEntity> wrapper = new QueryWrapper<AttrGroupEntity>();
        if (StringUtils.isNotEmpty(key)) {
            wrapper.and((obj) -> {
                obj.eq("attr_group_id", key).or().like("attr_group_name", key);
            });
        }
        if (catelogId == 0) { // 如果分类id=0 查询出所有的数据
            IPage<AttrGroupEntity> page = this.page(new Query<AttrGroupEntity>().getPage(params), wrapper);
            return new PageUtils(page);
        } else {
            // 分类id不为0,
            wrapper.eq("catelog_id", catelogId);
            IPage<AttrGroupEntity> page = this.page(new Query<AttrGroupEntity>().getPage(params), wrapper);
            return new PageUtils(page);
        }
    }

    @Override
    public List<AttrEntity> getAllRelationAttr(Long attrGroupId) {
        List<AttrAttrgroupRelationEntity> attrgroupRelationEntities = attrAttrgroupRelationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_group_id", attrGroupId));
        List<Long> attrIds = attrgroupRelationEntities.stream().filter((item) -> item != null).map((item) -> item.getAttrId()).collect(Collectors.toList());
        List<AttrEntity> attrEntityList = attrIds.stream().map((id) -> attrDao.selectById(id)).collect(Collectors.toList());
        return attrEntityList;
    }

    @Override
    public PageUtils getNoRelationAttr(Map<String, Object> params, Long attrGroupId) {
        List<AttrAttrgroupRelationEntity> attrgroupRelationEntities = attrAttrgroupRelationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().ne("attr_group_id", attrGroupId));
        List<Long> attrIds = attrgroupRelationEntities.stream().filter((item) -> item != null).map((item) -> item.getAttrId()).collect(Collectors.toList());
        QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("attr_id", attrIds);
        String key = (String) params.get("key");
        if (StringUtils.isNotEmpty(key)) {
            queryWrapper.eq("attr_id", key).or().like("attr_name", key);
        }
        IPage<AttrEntity> page = attrService.page(
                new Query<AttrEntity>().getPage(params),
                queryWrapper
        );
        List<AttrEntity> records = page.getRecords();
        PageUtils pageUtils = new PageUtils(page);
        pageUtils.setList(records);
        return pageUtils;

    }

    /**
     * 删除分组和属性的关联关系
     *
     * @param @attrGroupVo
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void deleteAttrGroupRelationAttr(List<AttrGroupVo> list) {
        if (list != null && list.size() > 0) {
            for (AttrGroupVo attrGroupVo : list) {
                AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = new AttrAttrgroupRelationEntity();
                BeanUtils.copyProperties(attrGroupVo, attrAttrgroupRelationEntity);
                QueryWrapper<AttrAttrgroupRelationEntity> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("attr_id", attrAttrgroupRelationEntity.getAttrId());
                queryWrapper.and(wrapper -> {
                    wrapper.eq("attr_group_id", attrAttrgroupRelationEntity.getAttrGroupId());
                });
                attrAttrgroupRelationDao.delete(queryWrapper);
                attrDao.deleteById(attrAttrgroupRelationEntity.getAttrId());
                log.info("删除关联关系成功");
            }
        }

    }

    /**
     * 新增分组和属性的关联关系
     *
     * @param
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void addRelationGroupAttr(List<AttrGroupVo> list) {

        if (list != null && list.size() > 0) {
            for (AttrGroupVo attrGroupVo : list) {
                AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = new AttrAttrgroupRelationEntity();
                attrAttrgroupRelationEntity.setAttrId(attrGroupVo.getAttrId());
                attrAttrgroupRelationEntity.setAttrGroupId(attrGroupVo.getAttrGroupId());
                // 校验是否数据库中是否有相同数据信息
                QueryWrapper<AttrAttrgroupRelationEntity> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("attr_id", attrGroupVo.getAttrId());
                queryWrapper.and((wrapper -> {
                    wrapper.eq("attr_group_id", attrAttrgroupRelationEntity.getAttrGroupId());
                }));

                Integer count = attrAttrgroupRelationDao.selectCount(queryWrapper);
                if (count > 0) {
                    throw new RuntimeException("存在相同条件的数据信息");
                }else{
                    attrAttrgroupRelationDao.insert(attrAttrgroupRelationEntity);
                }
            }
        }
    }

    /**
     *
     * @param catelogId
     * @return
     */
    @Override
    public List<CategoryGroupAttrRelationAttrVo> getCategoryGroupAttrRelationAttr(Long catelogId) {

        // 获取当前分类下的所有属性分组信息
        List<AttrGroupEntity> attrGroupEntities = this.list(new QueryWrapper<AttrGroupEntity>().eq("catelog_id", catelogId));
        // 获取分组下的所有属性信息（第一种）
//        List<CategoryGroupAttrRelationAttrVo> categoryGroupAttrRelationAttrVos = new ArrayList<>();
//        attrGroupEntities.stream().forEach((item) -> {
//            CategoryGroupAttrRelationAttrVo categoryGroupAttrRelationAttrVo = new CategoryGroupAttrRelationAttrVo();
//            BeanUtils.copyProperties(item,categoryGroupAttrRelationAttrVo);
//            Long attrGroupId = item.getAttrGroupId();
//            List<AttrAttrgroupRelationEntity> attrgroupRelationEntities = attrAttrgroupRelationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_group_id", attrGroupId));
//            List<AttrVo> attrVosList = attrgroupRelationEntities.stream().map((attr) -> {
//                AttrVo attrVo = new AttrVo();
//                Long attrId = attr.getAttrId();
//                AttrEntity attrEntity = attrService.getById(attrId);
//                BeanUtils.copyProperties(attrEntity,attrVo);
//                return attrVo;
//            }).collect(Collectors.toList());
//            categoryGroupAttrRelationAttrVo.setAttrs(attrVosList);
//            categoryGroupAttrRelationAttrVos.add(categoryGroupAttrRelationAttrVo);
//        });\
        // 第二种
        List<CategoryGroupAttrRelationAttrVo> relationAttrVos = attrGroupEntities.stream().map((item) -> {
            CategoryGroupAttrRelationAttrVo categoryGroupAttrRelationAttrVo = new CategoryGroupAttrRelationAttrVo();
            BeanUtils.copyProperties(item,categoryGroupAttrRelationAttrVo);
            List<AttrEntity> attrServiceGroupAttrRelation = attrService.getGroupAttrRelation(item.getAttrGroupId());
            List<AttrVo> voList = attrServiceGroupAttrRelation.stream().map((attr) -> {
                AttrVo attrVo = new AttrVo();
                BeanUtils.copyProperties(attr,attrVo);
                return attrVo;
            }).collect(Collectors.toList());
            categoryGroupAttrRelationAttrVo.setAttrs(voList);
            return categoryGroupAttrRelationAttrVo;
        }).collect(Collectors.toList());
        return relationAttrVos;
    }

}